const {
    mysql
  } = require('../../database/mysql')
  const Company = require('../../model/company')
  const Uuid = require('../../utils/uuid')
  
  class CompanyService {
    //添加新球场
    static async newCompany({
      ctx
    }) {
      let newCompanyInfo = {}
      newCompanyInfo = ctx.request.body
      const company = new Company(newCompanyInfo)
      company.id = new Uuid().uuid
      company.createdDate = new Date()
      const result = await mysql('company').insert(company.getData().company)
      return result[0] === 0 ? {
        result: true,
        company: company.getData().company
      } : {
        result: false
      }
    }
  
    //获取所有信息
    static async getAllCompany({ctx}) {
      let newCompanyInfo = {}
      newCompanyInfo = ctx.request.body
      const company = new Company(newCompanyInfo)
      const result = await mysql('company').where(company.getData().companyWithNoNull).select().orderBy('name', 'desc')
      const CompanysInfo = []
      result.forEach((CompanyInfo) => {
        CompanysInfo.push(CompanyInfo)
      })
      return CompanysInfo
    }

    // 根据id找用户
  static async getCompanyById({ id }) {
    console.log(id)
  
      const [companyInfo] = await mysql('company')
        .where({ id })
        .select()
    if(companyInfo) {
      const company = new Company(companyInfo)
      return company.getData()
    }else{
      return false
    }
  }
  
      //获取所有球场信息(带订单)
      static async getCompanyWithOrder({
        day1,day2,day3
     }) {
        const result = await mysql('company').select('company.*',
        {'day1':await mysql('order').select().where('company_id','=','company.id').andWhere({date:day1})
        },
        {'day2':
          await mysql('order').select().where('company_id','=','company.id').andWhere({date:day2})
        },
        {'day3':
          await mysql('order').select().where('company_id','=','company.id').andWhere({date:day3})
        }
        )
        const CompanysInfo = []
        result.forEach((CompanyInfo) => {
          CompanysInfo.push(CompanyInfo)
        })
        return CompanysInfo
      }
    // 删除某个球场
    static async delCompany({
      id
    }) {
      const result = await mysql('company')
        .where({
          id
        })
        .del()
  
      return result === 1
    }
    // 球场信息更新
    static async setCompany({
      ctx,
      id
    }) {
      let updateCompanyInfo = {}
      updateCompanyInfo = ctx.request.body
      const company = new Company(updateCompanyInfo)
      const updateInfo = company.getData().companyWithNoNull
      Reflect.deleteProperty(updateInfo, 'id')
      Reflect.deleteProperty(updateInfo, 'created_date')
      Reflect.deleteProperty(updateInfo, 'updated_date')
      const result = await mysql('company').where({
        id
      }).update(updateInfo)
      return result === 1
    }
  }
  
  
  module.exports = CompanyService